package kr.saeildamil.androidforstudy2.ch33;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MyCameraSurface extends SurfaceView implements SurfaceHolder.Callback {
	SurfaceHolder mHolder;
	Camera camera;

	public MyCameraSurface(Context context, AttributeSet attrs) {
		super(context, attrs);
		mHolder = getHolder();
		mHolder.addCallback(this);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
		try {
			camera.setPreviewDisplay(mHolder);
		} catch (IOException e) {
			camera.release();
			camera = null;
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Camera.Parameters params = camera.getParameters();
		List<Size> sizelist = params.getSupportedPreviewSizes();
		if(sizelist == null){
			params.setPreviewSize(width, height);
		}else{
			int diff = 10000;
			Size opti = null;
			for(Size s : sizelist){
				if(Math.abs(s.height - height) < diff){
					diff = Math.abs(s.height - height);
					opti = s;
				}
			}
			params.setPreviewSize(opti.width, opti.height);
		}
		camera.setParameters(params);
		camera.startPreview();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if(camera != null){
			camera.stopPreview();
			camera.release();
			camera = null;
		}
	}
}
